package com.shahouz.javaThreadPool;

import java.util.SortedSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @ProjectName: javaThreadPool
 * @Package: com.shahouz.javaThreadPool
 * @Description: 简单的线程池
 * @Author: tdl
 * @CreateDate: 2018/8/22 下午2:18
 **/
public class ThreadPoolService {
    private static final int THREAD_MAX = 5;

    private static final int WORKERS_QUEUE_INIT = 10;

    private static final int TASK_QUEUE_INIT = 10;

    /**
     * 工作线程队列
     */
    private final ArrayBlockingQueue<Worker> workers = new ArrayBlockingQueue<Worker>(WORKERS_QUEUE_INIT);

    /**
     * 任务队列
     */
    private final LinkedBlockingQueue<Runnable> jobs = new LinkedBlockingQueue<Runnable>(TASK_QUEUE_INIT);

    /**
     * 线程池初始化
     *
     * @return void
     */
    public void init(int amount) {
        if (amount == 0) {
            amount = THREAD_MAX;
        }
        if (amount > THREAD_MAX) {
            amount = THREAD_MAX;
        }
        for (int i = 0; i < amount; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread thread = new Thread(worker);
            // 试试是否为后台线程有什么差别
            // thread.setDaemon(true);
            thread.start();
            System.out.print("Get a new worker.\n");
        }
    }

    /**
     * 执行任务方法
     *
     * @param runnable 继承runnable的线程方法
     * @return void
     */
    public void execute(Runnable runnable) {


        // 检测空闲工作线程

        // 检测任务队列
        if(jobs.size() >= TASK_QUEUE_INIT) {

        }
        // 检测是否有额外工作线程可以创建

        // 执行饱和策略

        try {
            jobs.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addWorker() {

    }

    public void removeWorker() {

    }

    public class Worker extends Thread {
        private volatile boolean running = true;

        @Override
        public void run() {
            while (running) {
                System.out.print("Worker '" + Thread.currentThread().getName() + "' is on.\n");
                Runnable job = null;

                synchronized (jobs) {
                    try {
                        job = jobs.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (job != null) {
                    job.run();
                }
            }
        }

        // 终止该线程
        public void shutdown() {
            running = false;
        }
    }
}
